package com.acme.bankapp.domain.bank;

import java.util.Arrays;

/**
 * This class represents bank's client
 * 
 * @author Anton Kotov
 * 
 */
public class Client {

	public Client(String name, Gender gender, Account[] accounts) {
		this.name = name;
		this.gender = gender;
		this.accounts = accounts;
	}

	public Client(String name, Gender gender) {
		this(name, gender, null);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Gender getGender() {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	public Account[] getAccounts() {
		if (accounts == null)
			return null;

		Account[] newAccounts = new Account[accounts.length];
		System.arraycopy(accounts, 0, newAccounts, 0, accounts.length);
		return newAccounts;
	}

	public Client addAccount(Account account) {
		if (accounts == null) {
			accounts = new Account[1];
			accounts[0] = account;
			return this;
		}

		Account[] newAccounts = new Account[accounts.length + 1];
		System.arraycopy(accounts, 0, newAccounts, 0, accounts.length);
		newAccounts[accounts.length] = account;
		accounts = newAccounts;
		return this;
	}

	public String getClientSalutation() {
		return gender + " " + name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(accounts);
		result = prime * result + ((gender == null) ? 0 : gender.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Client)) {
			return false;
		}
		Client other = (Client) obj;
		if (!Arrays.equals(accounts, other.accounts)) {
			return false;
		}
		if (gender != other.gender) {
			return false;
		}
		if (name == null) {
			if (other.name != null) {
				return false;
			}
		} else if (!name.equals(other.name)) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer("Client [name=" + name
				+ ", gender=" + gender + ", accounts=");
		for (Account account : accounts) {
			buffer.append("\n\t");
			buffer.append(account);
		}
		buffer.append(']');
		return buffer.toString();
	}

	private String name;
	private Gender gender;

	private Account[] accounts;
}
